<!-- 机构端-招聘人才-职业证书 -->
<template>
  <view class="container">
    <!-- 说明文字 -->
    <view class="description">
      <text>说明：优先上传XXXXXX职业证书进行认证。也可添加其他种类证书</text>
    </view>

    <!-- 证书列表 -->
    <view class="certificate-list">
      <view class="certificate-item" v-for="(cert, index) in certificates" :key="index">
        <!-- 证书全名 -->
        <view class="form-item">
          <text class="label">证书全名</text>
          <u-input
            v-model="cert.jlzs_name"
            placeholder="请输入"
            :border="false"
            input-align="left"
          ></u-input>
        </view>

        <!-- 证书等级 -->
        <view class="form-item">
          <text class="label">证书等级</text>
          <u-input
            v-model="cert.jlzs_level"
            placeholder="请选择"
            :border="false"
            input-align="left"
            @click="showLevelPicker(index)"
						:focus="false"  
						disabled 
          ></u-input>
        </view>

        <!-- 证书照片 -->
        <view class="form-item">
          <text class="label">证书照片</text>
          <u-upload
					  ref="uploadRef"
				  	:action="action"
            :fileList="cert.photoList"
						@on-list-change="(list,name) =>onchange(list,name,index)"
            @on-remove="(e) => deletePic(e, index)"
						:auto-upload="false"
            :index="index"
            multiple
            :maxCount="1"
            width="160"
            height="160"
						:show-progress="false"						
          >
					<!--             @afterRead="(e) => afterRead(e, index)" -->
    <!--        <image
              v-if="cert.photoList === ''"
              src="/static/images/upload-placeholder.png"
              class="upload-placeholder"
            ></image> -->
          </u-upload>
        </view>

        <!-- 删除按钮（第二个及以后的证书显示） -->
        <view class="delete-btn" v-if="index > 0" @click="removeCertificate(index)">
          <u-icon name="trash" color="#ff4d4f" size="20"></u-icon>
          <text>删除</text>
        </view>
      </view>
    </view>

    <!-- 添加证书按钮 -->
    <view class="add-btn" @click="addCertificate">
      <u-icon name="plus" color="#2979ff" size="20"></u-icon>
      <text>添加证书</text>
    </view>

    <!-- 保存按钮 -->
    <view class="save-btn">
      <u-button type="primary" @click="saveCertificates" :custom-style="btuStyle" shape="circle" >保存</u-button>
    </view>

    <!-- 证书等级选择器 -->
		<u-picker v-model="showPicker" mode="selector" :range="levelParams" @confirm="confirmLevel"></u-picker>
  </view>
</template>

<script>
	import util from '@/utils/util.js'
export default {	
  data() {
    return {
			//按钮统一色彩
			btuStyle: {
				"backgroundColor": "#03B8CD",
				"color": "#ffffff",
				marginRight: '20rpx',
			},
			//图片上传地址
			action: '#',
      certificates: [
        {
					jlzs_code: '',
          jlzs_name: '证书1',
          jlzs_level: '中级',
          photoList: [] ,///存储照片url
					photoListId:'', ///存储照片服务端返回的id
        }
      ],
      showPicker: false,
      currentCertIndex: 0,
			levelParams: ['初级', '中级', '高级', '技师', '高级技师'],
			isEdit: false,
			isdelte: false,
    }
  },
	watch: {
	  // 当数据源变化时清空上传组件
	  dataSource(newVal) {
	    if (newVal) {
	      this.clearUploadComponent();
	    }
	  }
	},
	onLoad() {
		
	},
	onShow() {
		if(!this.isEdit) {
			this.selectZyZslist()
		} else {
			this.isEdit = false
		}
	},
  methods: {
		// 获取证书信息
		selectZyZslist() {
			this.$u.api.queryjlzyzslist({
				usercode: uni.getStorageSync('usercode')
			}).then(res=>{				
				let cert = res.data.base_info
				// 以下为数组每个对象增加相应的字段
				// cert = cert.map(item => ({
				//   ...item,          // 保留原有字段
				//   photoList: [],     // 新增字段
				// 	photoListID: []
				// }));
				// 处理证书的图片
				this.isEdit = true
				this.getZyZsValue(cert)
				console.log('证书:', cert)
			})
		},
		// 处理证书的图片
		getZyZsValue(cert) {
			let tmpcertificates = cert.sort((a, b) => a.id - b.id);
			this.certificates = []
			for (let i=0;  i< tmpcertificates.length; i++) {
				this.certificates.push({	
					jlzs_code: tmpcertificates[i].jlzs_code,
					jlzs_name: tmpcertificates[i].jlzs_name,
					jlzs_level: tmpcertificates[i].jlzs_level,
					photoListId: tmpcertificates[i].jlzs_img_uri[0].imguri
				})
				this.certificates[i].photoList = []
				if(this.certificates[i].photoList.length == 0) {
					this.certificates[i].photoList.push({
						url: tmpcertificates[i].jlzs_img_uri[0].url
					})
				}

			}	
			console.log('证书-1:', this.certificates)
		},
    // 添加证书
    addCertificate() {
      this.certificates.push({
				jlzs_code:'',
				jlzs_name: '',
				jlzs_level: '',
        photoList: [], ///存储照片url
				photoListId:''///存储照片服务端返回的id
      })
    },
		
		// 当图片变化时
		onchange(list,name,index) {
			this.isEdit = true
			console.log('图片变化时-name：',list,name,index)
			if(this.certificates[index].photoList.length == 0) {
				console.log('图片变化时-name-1：',list,name,index)
				if(list.length != 0){
					const file = list[0]
					console.log("onchange:", file.url)
					// 处理新准备上传的照片文件（添加必要字段）
					const newFiles = list.map(item => ({
						url: item.url, // 临时路径
					}))
					// console.log("onchange-1:", newFiles)
					// this.licenseFiles = file // 更新文件列表	
					// this.certificates.photoList = []
					// this.certificates[name].photoList = file.url
					this.certificates[name].photoList = [...this.certificates[name].photoList, ...newFiles];
					// console.log("onchange-2:", this.licenseFiles, list[0].url)
					
					// 将图片转换为Base64
					util.getPhotoBase64(file.url, base64 => {
						// console.log('main-bser64', base64)
						this.base64Data = base64
						// 转换成功后上传
						this.uploadBase64(name)
					})
					
				}
			}

		},
		
		// 上传Base64数据到服务器
		uploadBase64(index) {
			// console.log('upload:', this.base64Data)
			if (!this.base64Data) {
				uni.showToast({
					title: '请先选择图片',
					icon: 'none'
				})
				return
			}	
			uni.showLoading({
				title: '上传中...'
			})		
			this.$u.api.uploadres({
				"usercode": uni.getStorageSync('wxcode'),
				"rescode": this.base64Data,
				"restype": "0",
				"resdesc": "上传照片"
			}).then(res => {
				console.log('uploadres:', res)
				this.certificates[index].photoListId = res.data.base_info
			})
		},
		
    
    // 删除证书
    removeCertificate(index) {
      uni.showModal({
        title: '提示',
        content: '确定要删除此证书吗？',
        success: (res) => {
          if (res.confirm) {
            // this.certificates.splice(index, 1)
						this.$u.api.deletejlzyzs({
							"jlzscode": this.certificates[index].jlzs_code
						}).then(res => {
							console.log('delete:', res)	
							this.selectZyZslist()
						}).catch(err => {
							uni.showToast({
							  title: `删除失败，请重试！`,
							  icon: 'none'
							})
							
						})
          }
        }
      })
			console.log('delet',this.certificates)
    },
    
    // 删除图片
    deletePic(event,index) {
			console.log('删除',event,index)
      this.certificates[index].photoList.splice(event, 1)			
    },
		
    // 显示等级选择器
    showLevelPicker(index) {
      this.currentCertIndex = index
      this.showPicker = true
    },
    
    // 确认选择的等级
    confirmLevel(e) {
			this.certificates[this.currentCertIndex].jlzs_level = this.levelParams[e[0]]
    },
    
    
    // 保存证书
    saveCertificates() {
			console.log('保存证书：',this.certificates)
				// 验证必填字段
				for (let i = 0; i < this.certificates.length; i++) {
				  const cert = this.certificates[i]
				  if (!cert.jlzs_name || !cert.jlzs_level || cert.photoList.length === 0) {
				    uni.showToast({
				      title: `请完善第${i + 1}个证书的信息`,
				      icon: 'none'
				    })
				    return
				  } else {
						if(cert.jlzs_code !== '') {
							// 当有有jlzs_code存在时，即表示编辑
							// 若证书都正确填写了，就上传服务端
							this.$u.api.updatejlzyzs({
								"jlzscode": cert.jlzs_code,
								"jlzsname": cert.jlzs_name,
								"jlzslevel": cert.jlzs_level,
								"jlzsimguri": cert.photoListId,
							}).then(res =>{
								console.log('证书：', res)
								uni.navigateTo({
									url: '/pages/Practitioner/personMesume/personMesume'
								});
							})
						}	 else {
							// 添加
							// 若证书都正确填写了，就上传服务端
							this.$u.api.createjlzyzs({
								"usercode": uni.getStorageSync('usercode'),
								"jlzsname": cert.jlzs_name,
								"jlzslevel": cert.jlzs_level,
								"jlzsimguri": cert.photoListId,
							}).then(res =>{
								console.log('证书：', res)
								uni.navigateTo({
									url: '/pages/Practitioner/personMesume/personMesume'
								});
							})
						}					
					} 
				}
      }
      
      // 实际项目中这里调用保存API
      // uni.showLoading({
      //   title: '保存中...'
      // })
      
      // setTimeout(() => {
      //   uni.hideLoading()
      //   uni.showToast({
      //     title: '保存成功',
      //     icon: 'success'
      //   })
      //   // 可以跳转到其他页面或执行其他操作
      // }, 1000)

  }
}
</script>

<style lang="scss" scoped>
.container {
  padding: 20rpx;
  padding-bottom: 120rpx;
  background-color: #f7f7f7;
  min-height: 100vh;
}

.description {
  padding: 20rpx;
  font-size: 26rpx;
  color: #666;
  background-color: #fff;
  border-radius: 8rpx;
  margin-bottom: 20rpx;
}

.certificate-list {
  margin-bottom: 20rpx;
}

.certificate-item {
  background-color: #fff;
  border-radius: 8rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  position: relative;
  
  .form-item {
    display: flex;
		// justify-content: space-between;
    align-items: center;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
    
    .label {
      width: 160rpx;
      font-size: 28rpx;
      color: #333;
    }
    
    /deep/ .u-input {
      flex: 1;
    }
    
    /deep/ .u-upload {
      flex: 1;
    }
    
    .upload-placeholder {
      width: 160rpx;
      height: 160rpx;
      border: 1rpx dashed #e0e0e0;
      border-radius: 8rpx;
    }
  }
  
  .delete-btn {
    position: absolute;
    right: 20rpx;
    bottom: 20rpx;
    display: flex;
    align-items: center;
    color: #ff4d4f;
    font-size: 24rpx;
    
    .u-icon {
      margin-right: 5rpx;
    }
  }
}

.add-btn {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 80rpx;
  background-color: #fff;
  border-radius: 8rpx;
  color: #2979ff;
  font-size: 28rpx;
  margin-bottom: 20rpx;
  
  .u-icon {
    margin-right: 10rpx;
  }
}

.save-btn {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx;
  background-color: #fff;
  box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.05);
  
  /deep/ .u-btn {
    height: 80rpx;
    font-size: 32rpx;
  }
}
</style>